<template>
	<view :style="{height:PhoneInfo.windowHeight + 'px',width:PhoneInfo.windowWidth + 'px'}">
		<mvBar :mysNavConfig="mysNavConfig" @onLeftClick="onLeftClick"></mvBar>
		<u-toast ref="uToast"></u-toast>
		<view class="popage">
			<u-tabs :list="list" lineWidth="60" :scrollable='false' lineColor="#3c9cff" :activeStyle="{
				    color: '#303133',
				    fontWeight: 'bold',
				    transform: 'scale(1.05)'
				}" :inactiveStyle="{
				    color: '#606266',
				    transform: 'scale(1)'
				}" itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;" @click="clicktab">
			</u-tabs>
			<!-- 基础信息 -->
			<view v-show="number==1?true:false" style="margin-top: 2%;">
				<u-form labelPosition="left" :model="pointForm" ref="form1">
					<u-form-item label="测点名称" label-width="75" borderBottom prop="name" ref="item1">
						<u-input border="none" v-model="pointForm.name" maxlength="20" placeholder="请输入测点名称">
						</u-input>
					</u-form-item>
					<u-form-item label="转轴直径" label-width="75" borderBottom prop="Diameter" ref="item5">
						<u-input border="none" type="digit" v-model="pointForm.Diameter" placeholder="请输入转轴直径">
							<template slot="suffix">
								<view style="width: 35px; font-size: 17px;">mm</view>
							</template>
						</u-input>
					</u-form-item>
					<u-form-item label="测点轴转速" label-width="85" borderBottom prop="rotateSpeed" ref="item4">
						<u-input border="none" type="number" v-model="pointForm.rotateSpeed"
							@blur='countrev(pointForm.rotateSpeed)' placeholder="请输入测点轴转速">
							<template slot="suffix">
								<view style="width: 35px; font-size: 17px;">rpm</view>
							</template>
						</u-input>
					</u-form-item>
					<u-form-item
						:label="pointForm.deviceMac==''||pointForm.deviceMac==undefined||pointForm.deviceMac==null?'绑定传感器':'传感器编号: '+pointForm.deviceMac"
						label-width="200" borderBottom @click='sensor(pointForm.deviceMac)' prop="zAxis" ref="item8">
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="报警状态持续时间" labelWidth="130" borderBottom @click="show = true;hideKeyboard()">
						<u--input v-model="pointForm.AbnormalKeeping" disabled disabledColor="#ffffff"
							placeholder="请选择报警状态持续时间" border="none">
						</u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-picker closeOnClickOverlay :immediateChange='true' @cancel="show = false" @confirm="confirm"
						:show="show" :columns="columns" keyName="name"></u-picker>
					<u-form-item label="传感器X轴对应测点方向" label-width="170" borderBottom prop="xAxis" ref="item6">
						<u-input border="none" maxlength="6" v-model="pointForm.xAxis" placeholder="X轴对应测点方向">
						</u-input>
					</u-form-item>
					<u-form-item label="传感器Y轴对应测点方向" label-width="170" borderBottom prop="yAxis" ref="item7">
						<u-input border="none" maxlength="6" v-model="pointForm.yAxis" placeholder="Y轴对应测点方向">
						</u-input>
					</u-form-item>
					<u-form-item label="传感器Z轴对应测点方向" label-width="170" borderBottom prop="zAxis" ref="item8">
						<u-input border="none" maxlength="6" v-model="pointForm.zAxis" placeholder="Z轴对应测点方向">
						</u-input>
					</u-form-item>
					<u-form-item label="测点描述" label-width="75" borderBottom prop="description" ref="item2">
						<u--textarea confirmType='done' placeholder="请输入测点描述" v-model="pointForm.description"
							maxlength="100" :count="true"></u--textarea>
					</u-form-item>
					<u-form-item label="测点图片" label-width="75" borderBottom prop="picUrl" ref="item3">
						<u-upload name="picUrl" :fileList="fileList" @delete="deletePic" :previewFullImage="true"
							:maxCount="4">
						</u-upload>
						<view v-show="photoshow">
							<u-button shape='circle'
								color="linear-gradient(to right, rgb(6, 169, 237), rgb(96, 221, 165))" type="success"
								icon="camera" @click="chooseImg" text="选择图片"></u-button>
						</view>
					</u-form-item>
				</u-form>
			</view>
			<!-- 采集策略 -->
			<view v-show="number==2?true:false" style="margin-top: 2%;">
				<u-subsection bgColor='#fff' :list="curNowlist" fontSize='16' :current="curNow" @change="sectionChange">
				</u-subsection>
				<view v-for="(item,index) in Strategydata" :key="item.tacticsCondition">
					<view class="cardtitle">{{item.tacticsConditionName}}</view>
					<view v-show="curNow==0?true:false">
						<u-form labelPosition="left">
							<u-form-item label="采集时长(单位:秒/s)" label-width="150">
								<u-input border="none" type="number" v-model="item.dataLength" @blur='dataLength(item)'
									placeholder="请输入采集时长">
									<template slot="suffix">
										<view class="danwei">s</view>
									</template>
								</u-input>
							</u-form-item>
							<u-form-item label="存储间隔(单位:秒/s)" label-width="150">
								<u-input border="none" type="number" v-model="item.interval" @blur='interval(item)'
									placeholder="请输入存储间隔">
									<template slot="suffix">
										<view class="danwei">s</view>
									</template>
								</u-input>
							</u-form-item>
						</u-form>
					</view>
					<view v-show="curNow==1?true:false">
						<u-form labelPosition="left">
							<u-form-item label="是否采集波形数据" label-width="80%">
								<u-switch v-model="item.specialTactics[0].collectFlag"></u-switch>
							</u-form-item>
							<u-form-item label="存储间隔(单位:小时/h)" label-width="160">
								<u-input border="none" type="number" v-model="item.specialTactics[0].interval"
									@blur='waveinterval(item.tacticsCondition,item.specialTactics[0].code)'
									placeholder="请输入存储间隔">
									<template slot="suffix">
										<view class="danwei">h</view>
									</template>
								</u-input>
							</u-form-item>
						</u-form>
					</view>
					<view v-show="curNow==2?true:false">
						<u-form labelPosition="left">
							<u-form-item label="是否采集波形数据" label-width="80%">
								<u-switch v-model="item.specialTactics[1].collectFlag"></u-switch>
							</u-form-item>
							<u-form-item label="存储间隔(单位:小时/h)" label-width="160">
								<u-input border="none" type="number" v-model="item.specialTactics[1].interval"
									@blur='waveinterval(item.tacticsCondition,item.specialTactics[1].code)'
									placeholder="请输入存储间隔">
									<template slot="suffix">
										<view class="danwei">h</view>
									</template>
								</u-input>
							</u-form-item>
						</u-form>
					</view>
				</view>
			</view>
			<view style="width: 90%; margin: 10% auto;">
				<u-button shape='circle' color="linear-gradient(to right, rgb(39, 167, 225), rgb(65, 132, 234))"
					type="primary" text="确定" @click="submit"></u-button>
			</view>
		</view>
		<gmy-img-cropper ref="gmyImgCropper" cropperType="ratio" fileType="jpg" imgSrc="" @getImg="getImg">
		</gmy-img-cropper>
	</view>
</template>

<script>
	import gmyImgCropper from "../../components/gmy-img-cropper/gmy-img-cropper.vue"
	export default {
		components: {
			gmyImgCropper
		},
		data() {
			return {
				PhoneInfo: '',
				photoshow: true,
				mysNavConfig: {
					/* 占位开启  */
					navPadding: true,
					/* 背景 */
					bgColor: "#2979FF",
					/* 标题 （屏幕中心居中 两边图标中心居中使用slot center1） */
					navTitle: {
						text: "测点信息",
						color: "#ffffff",
						fontSize: "18px", // px upx rpx
						fontWeight: "500", // 100 - 700
					},
					isCustomFn: true,
					btnType: "type2",
					type2Config: {
						// 左图标
						leftPath: "/static/img/back.png",
						// 右图标
						rightPath: "/static/img/home.png",
						// 圆角
						radius: "40rpx",
					}
				},
				number: 1,
				list: [{
					id: 1,
					name: '基础信息'
				}, {
					id: 2,
					name: '采集策略',
				}],
				curNowlist: ['特征数据', '声音波形', '振动波形'],
				curNow: 0,
				show: false,
				columns: [
					[{
							id: 1,
							name: '一天',
						},
						{
							id: 2,
							name: '一周',
						},
						{
							id: 3,
							name: '一年',
						},
						{
							id: 4,
							name: '无期限',
						}
					]
				],
				userinfo: '',
				equipmentRealId: '',
				pointRealId: '',
				fileList: [],
				addlist: [],
				pointForm: {
					name: '',
					description: '', //描述
					rotateSpeed: '', //测点轴转速
					Diameter: '', //转轴直径
					xAxis: '',
					yAxis: '',
					zAxis: '',
					AbnormalKeeping: '', //报警状态持续时间
					AbnormalKeepingid: '',
					deviceMac: '', //传感器编号
				},
				//采集策略
				Strategydata: [],
				rules: {
					name: [{
							type: 'string',
							required: true,
							message: '请输入测点名称',
							trigger: ['change', 'blur'],
						},
						{
							min: 2,
							max: 20,
							message: '测点名称长度在0-20个字符之间',
							trigger: ['change', 'blur'],
						},
					],
					description: [{
							type: 'string',
							required: true,
							message: '请输入测点描述',
							trigger: ['change', 'blur'],
						},
						{
							type: 'string',
							min: 2,
							max: 100,
							message: '测点描述不能低于2个字并且不能超过100个字',
							trigger: ['change', 'blur'],
						},
					],
					rotateSpeed: [{
						type: 'number',
						required: true,
						message: '请输入测点轴转速',
						trigger: ['change', 'blur'],
					}],
					Diameter: [{
						type: 'number',
						required: true,
						message: '请输入转轴直径',
						trigger: ['change', 'blur'],
					}],
					xAxis: [{
						type: 'string',
						required: true,
						message: '请输入传感器X轴对应测点方向',
						trigger: ['change', 'blur'],
					}],
					yAxis: [{
						type: 'string',
						required: true,
						message: '请输入传感器Y轴对应测点方向',
						trigger: ['change', 'blur'],
					}],
					zAxis: [{
						type: 'string',
						required: true,
						message: '请输入传感器Z轴对应测点方向',
						trigger: ['change', 'blur'],
					}]
				},
				entrust: '',
				urlrouter: '',
			}
		},
		onLoad(parameter) {
			this.PhoneInfo = this.$utils.GetPhoneInfo();
			let parameterdata = JSON.parse(decodeURIComponent(parameter.content));
			this.userinfo = uni.getStorageSync('userinfo');
			this.equipmentRealId = parameterdata.equipmentRealId;
			this.pointRealId = parameterdata.pointRealId;
			this.entrust = parameterdata.entrust
			this.getpointinfo(this.pointRealId);
		},
		onReady() {
			this.$refs.form1.setRules(this.rules)
		},
		methods: {
			//采集策略分段器
			sectionChange(index) {
				this.curNow = index;
			},
			//点击横向列表
			clicktab(index) {
				this.number = index.id;
			},
			//点击传感器
			sensor(value) {
				if (value !== '' && value !== undefined && value !== null) {
					uni.navigateTo({
						url: '/pages/sensor/sensor?macCode=' + value
					})
				} else {
					uni.navigateTo({
						url: '/pages/sensor/addSensor?pointRealId=' + this.pointRealId +
							'&equipmentRealId=' + this.equipmentRealId
					})
				}
			},
			//获取测点信息
			getpointinfo(pointRealId) {
				uni.showLoading({
					title: "加载中...",
					mask: true,
				});
				uni.request({
					url: getApp().globalData.serverAddress + this.$uri.Uri_lookPointInfo.replace("{userRealId}",
							this.userinfo.userRealId)
						.replace("{equipmentRealId}", this.equipmentRealId)
						.replace("{pointRealId}", pointRealId),
					method: "GET",
					success: (res) => {
						if (res.statusCode !== 200) {
							this.$utils.showToast(this, '服务器错误,请联系技术支持人员!', 'error');
							return
						}
						if (res.data.code == 0) {
							var result = res.data.data;
							this.pointForm.name = result.name; //名称
							this.pointForm.description = result.description; //描述
							this.pointForm.rotateSpeed = result.speed; //测点轴转速
							this.pointForm.Diameter = result.diameter; //转轴直径
							this.pointForm.xAxis = result.customX;
							this.pointForm.yAxis = result.customY;
							this.pointForm.zAxis = result.customZ;
							this.pointForm.deviceMac = result.deviceMac; //传感器编号
							//报警状态持续时间
							this.pointForm.AbnormalKeepingid = result.abnormalKeeping;
							for (let item of this.columns[0]) {
								if (item.id == result.abnormalKeeping) {
									this.pointForm.AbnormalKeeping = item.name
								}
							}
							//测点照片
							if (result.picUrl[0] !== '') {
								for (var i = 0; i < result.picUrl.length; i++) {
									this.addlist.push({
										url: result.picUrl[i]
									})
									this.fileList.push({
										url: getApp().globalData.serverAddress + result.picUrl[i]
									});
									if (this.fileList.length < 4) {
										this.photoshow = true;
									} else {
										this.photoshow = false;
									}
								}
							}
							//采集策略
							this.Strategydata = result.collectTacticses;
							for (let item of this.Strategydata) {
								for (let tem of item.specialTactics) {
									tem.interval = Math.round(tem.interval / 3600);
								}
							}
						} else {
							this.$utils.showToast(this, res.data.msg, 'error');
						}
					},
					fail() {
						this.$utils.showToast(this, "加载失败！", 'error');
					},
					complete() {
						uni.hideLoading();
					}
				})
			},
			//根据测点轴转速计算正常情况下的采集时长
			countrev(value) {
				if (value == '') {
					this.$utils.showToast(this, "测点轴转速不能为空", 'warning');
					return;
				}
				if (isNaN(Number(value))) {
					this.$utils.showToast(this, "请输入数字！", 'warning');
					this.pointForm.rotateSpeed = '';
					return;
				}
				if (Number(value) <= 0) {
					this.$utils.showToast(this, "测点轴转速必须大于0", 'warning');
					this.pointForm.rotateSpeed = '';
					return;
				}
				var datatime = 32 * 60 / Number(value);
				if (datatime > 10) {
					this.Strategydata[0].dataLength = 10;
					uni.showModal({
						showCancel: false,
						confirmText: '我知道了',
						confirmColor: '#3c9cff',
						content: '已根据您输入的测点轴转速自动计算出采集策略中特征数据正常情况下采集时长为 10 秒',
					});
				} else {
					this.Strategydata[0].dataLength = Math.ceil(datatime);
					uni.showModal({
						showCancel: false,
						confirmText: '我知道了',
						confirmColor: '#3c9cff',
						content: '已根据您输入的测点轴转速自动计算出采集策略中特征数据正常情况下采集时长为 ' + this.Strategydata[0].dataLength + ' 秒',
					});
				}
			},
			//报警状态持续时间
			confirm(e) {
				this.pointForm.AbnormalKeeping = e.value[0].name;
				this.pointForm.AbnormalKeepingid = e.value[0].id;
				this.show = false;
			},
			//隐藏软键盘
			hideKeyboard() {
				uni.hideKeyboard()
			},
			//删除照片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
				this.addlist.splice(event.index, 1)
				if (this.fileList.length < 4) {
					this.photoshow = true;
				} else {
					this.photoshow = false;
				}
			},
			//选择
			chooseImg() {
				this.$refs.gmyImgCropper.chooseImage();
			},
			//裁剪
			getImg(e) {
				const result = this.uploadFilePromise(e);
				this.fileList.push({
					status: 'success',
					message: '',
					url: e
				})
				if (this.fileList.length < 4) {
					this.photoshow = true;
				} else {
					this.photoshow = false;
				}
				this.imgCropperShow = false;
			},
			// 上传照片
			uploadFilePromise(url) {
				uni.compressImage({
					src: url,
					quality: 10,
					success: res => {
						return new Promise((resolve, reject) => {
							let a = uni.uploadFile({
								url: getApp().globalData.serverAddress + this.$uri
									.Uri_Image.replace("{userRealId}", this.userinfo
										.userRealId),
								filePath: res.tempFilePath,
								name: 'file',
								success: (res) => {
									if (res.statusCode !== 200) {
										this.$utils.showToast(this, '服务器错误,请联系技术支持人员!',
											'error');
										return
									}
									setTimeout(() => {
										resolve(res.data.data)
										var obj = JSON.parse(res.data);
										this.addlist.push({
											url: obj.data[0]
										})
									}, 1000)
								}
							});
						})
					}
				})
			},
			//采集时长
			dataLength(value) {
				for (let item of this.Strategydata) {
					if (item.tacticsCondition == value.tacticsCondition) {
						if (item.dataLength == '') {
							this.$utils.showToast(this, '采集策略中特征数据' + item.tacticsConditionName + "情况下采集时长不能为空!",
								'warning');
							return;
						}
						if (isNaN(Number(item.dataLength))) {
							this.$utils.showToast(this, "请输入数字！", 'warning');
							item.dataLength = '';
							return;
						}
						if (Number(item.dataLength) <= 0 || Number(item.dataLength) > 10) {
							this.$utils.showToast(this, '采集策略中特征数据' + item.tacticsConditionName + "情况下采集时长范围在1-10秒之间!",
								'warning');
							item.dataLength = '';
							return;
						}
					}
				}
			},
			//存储间隔
			interval(value) {
				for (let item of this.Strategydata) {
					if (item.tacticsCondition == value.tacticsCondition) {
						if (item.interval == '') {
							this.$utils.showToast(this, '采集策略中特征数据' + item.tacticsConditionName + "情况下存储间隔不能为空!",
								'warning');
							return;
						}
						if (isNaN(Number(item.interval))) {
							this.$utils.showToast(this, "请输入数字！", 'warning');
							item.interval = '';
							return;
						}
						if (Number(item.interval) < 300) {
							this.$utils.showToast(this, '采集策略中特征数据' + item.tacticsConditionName + "情况下存储间隔最小为300秒!",
								'warning');
							item.interval = '';
							return;
						}
						if (Number(item.interval) > 21600) {
							this.$utils.showToast(this, '采集策略中特征数据' + item.tacticsConditionName + "情况下存储间隔最大为21600秒(6小时)!",
								'warning');
							item.interval = '';
							return;
						}
					}
				}
			},
			//声音,振动波形存储间隔
			waveinterval(id, code) {
				for (let item of this.Strategydata) {
					if (item.tacticsCondition == id) {
						for (let value of item.specialTactics) {
							if (value.code == code) {
								if (value.interval == '') {
									this.$utils.showToast(this, '采集策略中' + value.name + item.tacticsConditionName +
										"情况下存储间隔不能为空!", 'warning');
									return;
								}
								if (isNaN(Number(value.interval))) {
									this.$utils.showToast(this, "请输入数字！", 'warning');
									value.interval = '';
									return;
								}
								if (Number(value.interval) < 1) {
									this.$utils.showToast(this, '采集策略中' + value.name + item.tacticsConditionName +
										"情况下存储间隔最小为1小时!", 'warning');
									value.interval = '';
									return;
								}
								if (Number(value.interval) > 48) {
									this.$utils.showToast(this, '采集策略中' + value.name + item.tacticsConditionName +
										"情况下存储间隔最大为48小时!", 'warning');
									value.interval = '';
									return;
								}
							}
						}
					}
				}
			},
			// 修改测点
			submit() {
				this.$refs.form1.validate().then(res => {
					if (this.pointForm.Diameter <= 0) {
						this.$utils.showToast(this, "转轴直径必须大于0", 'warning');
						return;
					}
					if (this.pointForm.rotateSpeed <= 0) {
						this.$utils.showToast(this, "测点轴转速必须大于0", 'warning');
						return;
					}
					if (this.entrust == 0) {
						this.urlrouter = this.$uri.Uri_alterPoint;
					} else {
						this.urlrouter = this.$uri.Uri_entrustalterpoint;
					}
					let pointUpdateDto = new Object();
					pointUpdateDto.Name = this.pointForm.name;
					pointUpdateDto.Description = this.pointForm.description;
					pointUpdateDto.Speed = this.pointForm.rotateSpeed;
					pointUpdateDto.Diameter = this.pointForm.Diameter;
					pointUpdateDto.CustomX = this.pointForm.xAxis;
					pointUpdateDto.CustomY = this.pointForm.yAxis;
					pointUpdateDto.CustomZ = this.pointForm.zAxis;
					pointUpdateDto.AbnormalKeeping = this.pointForm.AbnormalKeepingid
					pointUpdateDto.PicUrl = '';
					if (this.addlist.length > 0) {
						var arrlis = []
						for (let item of this.addlist) {
							arrlis.push(item.url)
						}
						pointUpdateDto.PicUrl = arrlis.join(",")
					}
					for (let item of this.Strategydata) {
						if (item.interval == '') {
							this.$utils.showToast(this, '采集策略中特征数据' + item.tacticsConditionName + "情况下存储间隔不能为空!",
								'warning');
							return;
						} else if (item.dataLength == '') {
							this.$utils.showToast(this, '采集策略中特征数据' + item.tacticsConditionName + "情况下采集时长不能为空!",
								'warning');
							return;
						} else {
							for (let it of item.specialTactics) {
								if (it.interval == '') {
									this.$utils.showToast(this, '采集策略中' + it.name + item.tacticsConditionName +
										"情况下存储间隔不能为空!",
										'warning');
									return;
								}
							}
						}
					}
					pointUpdateDto.CollectTacticses = this.Strategydata;
					for (let item of pointUpdateDto.CollectTacticses) {
						for (let tem of item.specialTactics) {
							tem.interval = tem.interval * 3600;
						}
					}
					uni.showLoading({
						title: "修改中...",
						mask: true,
					});
					uni.request({
						url: getApp().globalData.serverAddress + this.urlrouter.replace(
								"{userRealId}", this.userinfo.userRealId)
							.replace("{equipmentRealId}", this.equipmentRealId)
							.replace("{pointRealId}", this.pointRealId),
						data: JSON.stringify(pointUpdateDto),
						dataType: "json",
						method: "POST",
						success: (res) => {
							if (res.statusCode !== 200) {
								this.$utils.showToast(this, '服务器错误,请联系技术支持人员!', 'error');
								return
							}
							if (res.data.code == 0) {
								this.$utils.showToast(this, '修改成功！', 'success', 5);
							} else {
								this.$utils.showToast(this, res.data.msg, 'error');
							}
						},
						fail: () => {
							this.$utils.showToast(this, '修改失败！', 'error');
						},
						complete: () => {
							uni.hideLoading();
						}
					})
				}).catch(errors => {
					this.$utils.showToast(this, '请填写正确的信息！', 'warning');
				})
			},
			//返回上一级
			onLeftClick() {
				uni.navigateBack({
					delta: 1
				});
			}
		}
	}
</script>

<style lang="scss">
	.u-input__content {
		z-index: 0;
	}

	.u-textarea {
		z-index: 0;
	}

	.u-upload__deletable {
		z-index: 0 !important;
	}
</style>
<style lang="scss" scoped>
	.danwei {
		width: 35px;
		font-size: 17px;
		text-align: center;
	}

	.cardtitle {
		color: #3c9cff;
		text-align: center;
		font-size: 16px;
		margin-top: 2%;
		font-weight: bold;
	}

	.popage {
		width: 90%;
		margin: 5% auto;
		padding: 2% 5%;
		background-color: #ffffff;
		border-radius: 15px;
	}
</style>